#!/usr/bin/python3 

# this script is using to create a .config configuration file

import sys
import os
import json


argc = 0

for name in sys.argv:
    argc += 1

def fatal(msg):
    sys.stderr.write("%s: fatal: %s\n" % (sys.argv[0], msg))
    exit(1)


if argc != 1:
    fatal("no argument this requires")

if os.getcwd()[-7 : -1] == "script":
    fatal("call this as scripts/do_mkconfig.py, not ./do_mkconfig.py")


basedir = os.getcwd()
config_filename = basedir + "/include/config.h"
kconfig_filename = basedir + "/Kconfig"

# unlike that in linux, Kconfig is just a json likes that: 
# [
#   {
#       "name": "descr"
#   }, 
#   {
#        "DISABLE_A": "will you disable A"
#   }
# ]

try:
    open(config_filename, "r")
    print("%s exists. remove it if you want to config again. " % basedir + "/include/config.h")

    exit(0)

except FileNotFoundError:
    pass


try:
    kconfig_fd = open(kconfig_filename, "r")

except FileNotFoundError:
    fatal("Kconfig not exists")

out_fd = open(config_filename, "w")


kconfig_jsonobj = json.load(kconfig_fd)
kconfig_fd.close()

if type(kconfig_jsonobj) != list:
    fatal("Kconfig should be a json list object, but %s gave" % type(kconfig_jsonobj))


for config in kconfig_jsonobj:
    for key, descr in config.items():
        print("CONFIG %s: " % key)
        print("\t(" + descr + ")")

        value = input("> (int) ")
        
        try:
            value = int(value)

        except ValueError:
            fatal("an integer requires for %s" % key)

        out_fd.write("#define %s \t\t\t(%d)\n" % (key, value))
        print("\n")

